package ua.ck.example.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ua.ck.example.domain.Product;

@Repository
public class ProductDAOImpl implements ProductDAO {

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> listProducts() {
		return sessionFactory.getCurrentSession().createQuery("from Product")
				.list();
	}

	@Override
	public void addProduct(Product product) {
		sessionFactory.getCurrentSession().save(product);

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getProducts(Product product) {
		StringBuffer sql = new StringBuffer("FROM Product p WHERE 1=1");
		if (product.getProductId() != null) {
			sql.append(" and p.productId=" + product.getProductId());
		}
		if (product.getProductName() != null
				&& !product.getProductName().isEmpty()) {
			sql.append(" and p.productName like '%" + product.getProductName()
					+ "%'");
		}

		return (List<Product>) sessionFactory.getCurrentSession()
				.createQuery(sql.toString()).list();

	}

	@Override
	public void delProducts(Product product) {
		sessionFactory.getCurrentSession().delete(product);

	}

}
